package demo1;

//客户端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String Ip;
    private int port;
    public UdpEchoClient(String Ip,int port) throws SocketException {
        socket = new DatagramSocket();
        this.Ip = Ip;
        this.port = port;
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner in = new Scanner(System.in);
        while (true) {
            System.out.print("请输入你的请求：");
            //1.输入请求
            String request = in.nextLine();
            //2.发送请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(Ip),port);
            socket.send(requestPacket);
            //3.接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.打印请求
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //System.out.println("中文翻译为："+response);
            System.out.println("响应为："+response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",1314);//绑定本主机的服务器
        client.start();
    }
}